# -*- encoding:utf-8 -*-
# @Time: 2022/10/28 20:09
# @Author : moran
# @Email: moran@maqu.com
# @File: verifyUtil.py
# @Software: PyCharm
import os
import random
import string
from PIL import Image, ImageFont, ImageDraw, ImageFilter
from django_redis import get_redis_connection

from config.dbs.redis_rev import LOGIN_KEY_TEMPLATE


class ImageVerify:
    def __init__(self, x=140, y=40, length=4, size=28):
        """
        初始化
        :param x: 图片宽度
        :param y: 图片高度
        :param length: 字符的个数
        :param size: 字体大小
        """
        self.x = x
        self.y = y
        self.length = length
        self.size = size

    def random_str(self):
        """
        随机生成指定长度的字符串
        数据源：26个字母和10个数字
        :return: 生成的字符串
        """
        source = string.ascii_letters + string.digits
        return ''.join(random.sample(source, self.length))

    def random_color(self, start=0, end=255):
        """
        随机生成RGB颜色
        :param start: 颜色范围的最小值
        :param end: 颜色范围的最大值
        :return: tuple(r,g,b) 0-255
        """
        res = [random.randint(start, end) for i in range(3)]
        return tuple(res)

    def random_lines(self, draw):
        """
        绘制干扰线
        :param draw: draw对象 画笔
        :return:
        """
        for i in range(self.length):
            lines = [(random.randint(0, self.x),random.randint(0,self.y)) for i in range(2)]
            draw.line(lines, fill=self.random_color(64,200))

    def random_points(self, draw, rate):
        """
        绘制干扰点
        :param draw: 画笔
        :param rate: 频率
        :return:
        """
        for x in range(self.x):
            for y in range(self.y):
                if random.randint(1, 100) <= rate:
                    draw.point((x,y), fill=self.random_color(64,200))

    def verify_code(self):
        """
        生成验证码图片
        :return: 图片及正确答案
        """
        # 创建image对象 创建画布
        image = Image.new('RGB', (self.x, self.y), (255,255,255))  # 白色背景画布

        # 创建font对象 字体
        file = os.path.dirname(os.path.abspath(__file__))
        font = ImageFont.truetype(f'{file}/HYYakuHei-85W.ttf', self.size)

        # 创建draw对象 画笔，绘制图形，线，点
        draw = ImageDraw.Draw(image)

        # 绘制干扰线与干扰点
        self.random_lines(draw)
        self.random_points(draw, 15)

        # 随机生成字符答案，验证码值
        code = self.random_str()

        # 用画笔将font类型的字体对应的进行字符内容和颜色的绘制
        for i in range(self.length):
            draw.text((35*i+5,3), code[i], font=font, fill=self.random_color(30,128))

        # 模糊滤镜
        image = image.filter(ImageFilter.BLUR)

        # 返回图形及验证码值
        return image, code

def jwt_token(token, user=None, request=None):
    """
    自定义登录成功后的响应函数，登录后的数据处理
    执行这个函数，账号密码肯定正确了，手动校验验证码即可
    :param token: 令牌
    :param user: 登录的用户
    :param request: 请求对象
    :return: 登录接口响应的内容，token
    """
    param = request.data
    uuid = param.get('uuid')
    verify = param.get('verify')

    if not uuid or not verify:
        return {'msg': '请输入验证码'}

    # 得到redis缓存的该客户端验证码答案与传入进来的答案进行对比判断
    cache = get_redis_connection(alias='verify_codes')
    redis_verify = cache.get(LOGIN_KEY_TEMPLATE % uuid)
    cache.delete(LOGIN_KEY_TEMPLATE % uuid)

    if not redis_verify:
        return {'msg': '验证码过期'}

    if redis_verify.upper() != verify.upper():
        return {'msg': '验证码错误'}

    return {
        'token': token,
        'id': user.id,
        'username': user.username,
        'avatar': user.userdetail.avatar if hasattr(user, 'userdetail') else None
    }


if __name__ == '__main__':
    imgVerify = ImageVerify()
    img,code = imgVerify.verify_code()
    # with open('test.png', 'wb') as fp:
    #     img.save(fp)
    print(code)


